package test.y2020.image;


import cn.hutool.core.lang.ObjectId;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * Created By  醉美柳舞之众星捧月
 *
 * @author songx
 * @date 2020/3/2 10:23
 */
public class DrawingUtils {


    private static OSSClient ossClient;

    private static final String accessKeyId = "LTAIt2AFzdL98mur";
    private static final String endpoint = "oss-cn-shenzhen.aliyuncs.com";
    private static final String bucketName = "b2c-integration-test-public";
    private static final String secretAccessKey = "qeUPGTBsg4gGTCYKEgdEvAPxCKkPXC";


    /**
     * @return : java.lang.String
     * @Description : 将二维码图片和文字生成到一张图片上
     * @Param : originalImg 原图
     * @Param : qrCodeImg 二维码地址
     * @Param : shareDesc 图片文字
     * @Date : 2018/8/15
     */
    public static String generateImg(String originalImg, String qrCodeImg, String shareDesc) throws Exception {
        // 加载原图图片
        BufferedImage imageLocal = ImageIO.read(new URL(originalImg));
        // 加载用户的二维码
        BufferedImage imageCode = ImageIO.read(new URL(qrCodeImg));
        // 以原图片为模板
        Graphics2D g = imageLocal.createGraphics();
        AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
        g.setComposite(ac);
        g.setBackground(Color.WHITE);
        // 在模板上添加用户二维码(地址,左边距,上边距,图片宽度,图片高度,未知)
        g.drawImage(imageCode, 100, imageLocal.getHeight() - 190, 160, 158, null);
        // 设置文本样式
        g.setFont(new Font("微软雅黑", Font.PLAIN, 40));
        g.setColor(Color.red);
        // 计算文字长度，计算居中的x点坐标
        g.drawString(shareDesc, imageLocal.getWidth() - 330, imageLocal.getHeight() - 530);

        // 设置文本样式
        g.setFont(new Font("微软雅黑", Font.PLAIN + Font.BOLD, 16));
        g.setColor(Color.WHITE);
        // 计算文字长度，计算居中的x点坐标
        String press = "长按二维码";
        g.drawString(press, 105, imageLocal.getHeight() - 10);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        saveAsJpeg(imageLocal, out);
        out.close();
        return urlImgDownInputStream(new ByteArrayInputStream(out.toByteArray()));
    }

    /**
     * 以JPEG编码保存图片
     *
     * @param imageToSave 要处理的图像图片
     * @param fos         文件输出流
     * @throws IOException 抛出IO异常
     */
    private static void saveAsJpeg(BufferedImage imageToSave, ByteArrayOutputStream fos) throws IOException {
        ImageWriter imageWriter = ImageIO.getImageWritersBySuffix("jpg").next();
        ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
        imageWriter.setOutput(ios);
        /* 图片清晰比率 */
        float jpegCompression = 0.75f;
        // new Compression
        JPEGImageWriteParam jpegParams = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
        jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
        jpegParams.setCompressionQuality(jpegCompression);

        // new Write and clean up
        ImageIO.setUseCache(false);
        imageWriter.write(new IIOImage(imageToSave, null, null));
        ios.close();
        imageWriter.dispose();
    }

    /**
     * 图片流远程上传
     *
     * @param inStream 入参流
     * @date 2018年10月19日 下午5:07:24
     */
    private static String urlImgDownInputStream(InputStream inStream) {

        String currentPicName = String.format("%s-%s.png", "vps", ObjectId.next());
        PutObjectRequest req = new PutObjectRequest(bucketName, currentPicName, inStream);
        try {
            putObject(ossClient, req);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getOssResourceUri(bucketName, endpoint, currentPicName);

    }

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        System.out.println("开始：" + startTime);
        try {
            String originalImg = "https://blog.s-name.com/upload/2020/2/elasticsearch-d6fdb40c9b714e129a4650fac76297c8.jpg";
            String qrCodeImg = "https://blog.s-name.com/upload/2020/2/zookeeper-dc992824cfa94db1a90ef909957038b6.jpg";
            String shareDesc = "原价9999.99元";
            String img = generateImg(originalImg, qrCodeImg, shareDesc);
            System.out.println("生成完毕,url=" + img);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("结束：" + (System.currentTimeMillis() - startTime) / 1000);
    }


    public static String getOssResourceUri(String bucketName, String endPoint, String key) {
        return String.format("https://%s.%s/%s", bucketName, endPoint, key);
    }

    public static void putObject(OSSClient client, PutObjectRequest putObjectRequest) throws Exception {
        try {
            System.out.println("上传object到名为：" + putObjectRequest.getBucketName() + "的bucket");
            PutObjectResult putObjectResult = client.putObject(putObjectRequest);
            if (putObjectRequest.getCallback() != null) {
                byte[] buffer = new byte[1024];
                putObjectResult.getCallbackResponseBody().read(buffer);
                putObjectResult.getCallbackResponseBody().close();
            }
        } catch (OSSException oe) {
            throw new Exception(oe.getErrorMessage(), oe);
        } catch (ClientException ce) {
            throw new Exception(ce.getErrorMessage(), ce);
        }
    }
}
